<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryTeamBillParam" class="demo-form-inline">
              <el-form-item label="班组名称">
                <el-input v-model="queryTeamBillParam.TeamName" placeholder="请输入" clearable style="width: 200px" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchTeamBill()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addTeamBill()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionTeamBill()">批量删除</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="teamNo" label="编码" width="180" />
              <el-table-column prop="teamName" label="名称" width="180" />
              <el-table-column prop="teamType.teamTypeNO" label="类型编号" width="180" />
              <el-table-column prop="icon" label="类型名称" width="180" align="center">
                <template #default="scope">
                  <el-button type="primary" round size="small" v-if="scope.row.teamType.teamTypeName === '白班'">{{
                    scope.row.teamType.teamTypeName
                  }}</el-button>
                  <el-button type="info" round size="small" v-else>{{ scope.row.teamType.teamTypeName }}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="user.jobNumber" label="组长工号" width="180" />
              <el-table-column prop="user.userName" label="组长姓名" width="180" />
              <el-table-column prop="creator" label="创建人" width="180" />
              <el-table-column prop="updator" label="修改人" width="180" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="140">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteTeamBillSingle(scope.row.id)">
                    删除
                  </el-button>

                  <el-button type="primary" plain size="small" @click="UpdateTeamBill(scope.row)">更新</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryTeamBillParam.PageIndex"
                v-model:page-size="queryTeamBillParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryTeamBillParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>

    <div>
      <!-- 添加班组 -->
      <el-dialog
        v-model="centerDialogVisible"
        width="65%"
        title="添加班组"
        append-to-body
        :before-close="CreateTeamBillhandleClose"
      >
        <el-row>
          <el-col :span="24">
            <el-form
              :inline="true"
              ref="CreateTeamBillFormRef"
              :model="CreateTeamBillForm"
              label-width="auto"
              class="demo-form-inline"
              :rules="CreateTeamBillRules"
            >
              <el-form-item label="班组编号" prop="TeamNo">
                <el-input v-model="CreateTeamBillForm.TeamNo" placeholder="不输入则自动生成" style="width: 260px">
                </el-input>
              </el-form-item>
              <el-form-item label="班组名称" prop="TeamName">
                <el-input v-model="CreateTeamBillForm.TeamName" placeholder="请输入" style="width: 260px"> </el-input>
              </el-form-item>

              <el-form-item label="组长姓名" prop="UserId">
                <el-select
                  v-model="CreateTeamBillForm.UserId"
                  filterable
                  placeholder="请选择"
                  clearable
                  style="width: 260px"
                >
                  <el-option
                    v-for="option in UserinfoOptions"
                    :key="option.key"
                    :label="option.userName"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="班组类型" prop="TeamTypeId">
                <el-select
                  v-model="CreateTeamBillForm.TeamTypeId"
                  filterable
                  placeholder="请选择"
                  style="width: 260px"
                  clearable
                >
                  <el-option
                    v-for="option in TeamTypeOptions"
                    :key="option.key"
                    :label="option.teamTypeName"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="备注" prop="Remark">
                <el-input v-model="CreateTeamBillForm.Remark" type="textarea" style="width: 260px" />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-divider content-position="left" style="margin: 15px 0">组员信息</el-divider>

        <!-- 添加班组明细按钮 -->
        <el-row>
          <el-col :span="24">
            <div class="TeamBillfunctionbutton">
              <el-button type="primary" plain @click="addeamBillDetia()">添加人员</el-button>
              <el-button type="danger" plain @click="batchDeletioneamBillDetia()">清空列表</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 班组人员明细数据表格 -->
        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="tableloading"
              :data="TeamBillDetialData"
              height="300px"
              border
              style="width: 100%"
              max-height="300px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="jobNumber" label="工号" />
              <el-table-column prop="userName" label="姓名" />
              <el-table-column prop="department.departmentName" label="部门" />
              <el-table-column prop="roleinfo.roleName" label="职称" />

              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteTeamBillDetialSingle(scope.row.id)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="CreateTeamBillhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateTeamBillDialog(CreateTeamBillFormRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择用户信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectUserinfoFormtableData"
        :dialogVisible="SelectUserinfoDialogVisible"
        @selected="handleSelectedUserData"
        @closed="handleDialogClosedUser"
        @QueryForm="QueryForms"
      />
    </div>

    <div>
      <!-- 修改班组 -->
      <el-dialog v-model="UpdateDialogVisible" width="65%" title="修改班组" append-to-body>
        <el-row>
          <el-col :span="24">
            <el-form
              :inline="true"
              ref="UpdateTeamBillFormRef"
              :model="UpdateTeamBillForm"
              label-width="auto"
              class="demo-form-inline"
              :rules="CreateTeamBillRules"
            >
              <el-form-item label="班组编号" prop="TeamNo">
                <el-input
                  v-model="UpdateTeamBillForm.TeamNo"
                  disabled
                  placeholder="不输入则自动生成"
                  style="width: 260px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="班组名称" prop="TeamName">
                <el-input v-model="UpdateTeamBillForm.TeamName" placeholder="请输入" style="width: 260px"> </el-input>
              </el-form-item>

              <el-form-item label="组长姓名" prop="UserId">
                <el-select
                  v-model="UpdateTeamBillForm.UserId"
                  filterable
                  placeholder="请选择"
                  clearable
                  style="width: 260px"
                >
                  <el-option
                    v-for="option in UserinfoOptions"
                    :key="option.key"
                    :label="option.userName"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="班组类型" prop="TeamTypeId">
                <el-select
                  v-model="UpdateTeamBillForm.TeamTypeId"
                  filterable
                  placeholder="请选择"
                  style="width: 260px"
                  clearable
                >
                  <el-option
                    v-for="option in TeamTypeOptions"
                    :key="option.key"
                    :label="option.teamTypeName"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="备注" prop="Remark">
                <el-input v-model="UpdateTeamBillForm.Remark" type="textarea" style="width: 260px" />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-divider content-position="left" style="margin: 15px 0">组员信息</el-divider>

        <!-- 添加班组明细按钮 -->
        <el-row>
          <el-col :span="24">
            <div class="TeamBillfunctionbutton">
              <el-button type="primary" plain @click="addeamBillDetia()">添加人员</el-button>
              <el-button type="danger" plain @click="batchDeletioneamBillDetia()">清空列表</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 班组人员明细数据表格 -->
        <el-row>
          <el-col :span="24">
            <el-table
              v-loading="tableloading"
              :data="TeamBillDetialData"
              height="300px"
              border
              style="width: 100%"
              max-height="300px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="jobNumber" label="工号" />
              <el-table-column prop="userName" label="姓名" />
              <el-table-column prop="department.departmentName" label="部门" />
              <el-table-column prop="roleinfo.roleName" label="职称" />

              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" plain size="small" @click="DeleteTeamBillDetialSingle(scope.row.id)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="UpdateTeamBillhandleClose">取消</el-button>
            <el-button type="primary" @click="UpdateTeamBillDialog(UpdateTeamBillFormRef)">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择用户信息 -->
      <!-- <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectUserinfoFormtableData"
        :dialogVisible="SelectUserinfoDialogVisible"
        @selected="handleSelectedUserData"
        @closed="handleDialogClosedUser"
        @QueryForm="QueryForms"
      /> -->
    </div>
  </div>
</template>


<script setup lang="ts">
import ChildComponent from '@/components/CustomSelectDataDialog.vue'
import { ref, Ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiGetCrew_TeamBillPageListAsync,
  ApiGetCrew_TeamBillDetialPageListAsync,
  ApiDeletionCrew_TeamBillAsync,
  ApiCreateCrew_TeamBillAsync,
  ApiUpdateCrew_TeamBillAsync
} from '../../api/crew/CrewTeamBillApi'
import { ApiGetCrew_TeamTypePageListAsync } from '../../api/crew/CrewTeamTypeApi'
import { ApiGetBasicData_UserinfoPageListAsync } from '@/api/basic/basicDataUserinfoApi'
import { formatTime, capitalizeFirstLetter } from '../../utils/index'

// 定义接口和设置
interface TeamBillParam {
  TeamName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}

interface TeamBill {
  id: string
}

// 响应式变量
const tableloading = ref(false)
const UpdateDialogVisible = ref(false)
const centerDialogVisible = ref(false)
const SelectUserinfoDialogVisible = ref(false)
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const CreateTeamBillFormRef = ref<FormInstance>()

// 表单数据和验证规则
const CreateTeamBillForm: TeamBill = reactive({ id: '' })

const queryTeamTypeParam = reactive({ TeamTypeName: '', PageIndex: 1, PageSize: 100, totalCount: 0 })
const UserinfoOptions = ref([])
const TeamTypeOptions = ref([])
const UpdateTeamBillForm: TeamBill = reactive({ id: '' })
const CreateTeamBillRules = reactive({
  TeamName: [{ required: true, message: '班组名称不能为空', trigger: 'blur' }],
  UserId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  TeamTypeId: [{ required: true, message: '类型不能为空', trigger: 'blur' }]
})

// 查询参数
const queryTeamBillParam: TeamBillParam = reactive({
  TeamName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])
const TeamBillDetialData = ref<User[]>([])

// 用户
interface User {
  userName: ''
  PageIndex: 1
  PageSize: 100
  totalCount: 0
}
// 选择用户查询条件
const queryUserinfoParam = reactive({ userName: '', PageIndex: 1, PageSize: 100 })
//选择用户表格数据
const SelectUserinfoFormtableData = ref([])
// 选择用户查询列
const querycolumns = [
  { prop: 'jobNumber', label: '工号' },
  { prop: 'userName', label: '姓名' },
  { prop: 'departmentName', label: '部门' }
]
// 选择用户信列
const columns = [
  { prop: 'jobNumber', label: '工号' },
  { prop: 'userName', label: '姓名' },
  { prop: 'sex', label: '性别' },
  { prop: 'phoneNo', label: '手机号' },
  { prop: 'roleinfo.roleName', label: '职称' },
  { prop: 'department.departmentName', label: '部门' }
]

// 关闭修改对话框
const UpdateTeamBillhandleClose = () => {
  UpdateDialogVisible.value = false
}

// 打开更新班组设置信息对话框
const UpdateTeamBill = (row: { [key: string]: string | number }) => {
  Object.assign(UpdateTeamBillForm, capitalizeFirstLetter(row))

  UpdateDialogVisible.value = true

  //获取用户信息
  ApiGetBasicData_UserinfoPageListAsync(queryUserinfoParam).then((res) => {
    UserinfoOptions.value = res.data.data
  })
  // 获取班组类型
  ApiGetCrew_TeamTypePageListAsync(queryTeamTypeParam).then((res) => {
    TeamTypeOptions.value = res.data.data
  })

  // 用户人员列表
  queryTeamBillParam.TeamId = row.id
  ApiGetCrew_TeamBillDetialPageListAsync(queryTeamBillParam).then((res) => {
    TeamBillDetialData.value = res.data.data
  })
}

// 确认更新班组设置信息
const UpdateTeamBillFormRef = ref<FormInstance>()
const UpdateTeamBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (TeamBillDetialData.value.length < 1) {
        ElNotification({
          message: '请先添加人员',
          offset: 100,
          type: 'warning',
          duration: 2000
        })
        return
      }
      // 提取 TeamBillDetialData 中的 id 组成一个集合
      UpdateTeamBillForm.userIds = TeamBillDetialData.value.map((item) => item.id)
      ApiUpdateCrew_TeamBillAsync(UpdateTeamBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateDialogVisible.value = false
          SearchTeamBill()
        }
      })
    }
  })
}

//选择用户对话框确定操作
const handleSelectedUserData = (selectedData: User[]) => {
  let duplicateCount = 0
  let addedCount = 0

  selectedData.forEach((item) => {
    if (TeamBillDetialData.value && Array.isArray(TeamBillDetialData.value)) {
      if (!TeamBillDetialData.value.some((data) => data.id === item.id)) {
        TeamBillDetialData.value.push(item)
        addedCount++
      } else if (Array.isArray(TeamBillDetialData.value)) {
        duplicateCount++
      }
    } else {
      // 处理TeamBillDetialData.value为null或者非数组的情况
      TeamBillDetialData.value = selectedData
      addedCount = selectedData.length
    }
  })

  if (duplicateCount > 0) {
    ElNotification({
      message: `存在重复 ${duplicateCount} 条，已成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'warning',
      duration: 3500
    })
  } else {
    ElNotification({
      message: `成功添加 ${addedCount} 条数据`,
      offset: 100,
      type: 'success',
      duration: 2000
    })
  }
}

//添加明细移除
const DeleteTeamBillDetialSingle = (rowId: string) => {
  const rowidindex = TeamBillDetialData.value.findIndex((g) => g.id === rowId)
  if (rowidindex != -1) {
    TeamBillDetialData.value.splice(rowidindex, 1)
  }
}

// 对话框关闭后执行的逻辑
const handleDialogClosedUser = () => {
  SelectUserinfoDialogVisible.value = false
}

//选择用户对话框查询操作
const QueryForms = (form: User) => {
  ApiGetBasicData_UserinfoPageListAsync(form).then((res) => {
    SelectUserinfoFormtableData.value = res.data.data
  })
}

//添加班组人员明细
const addeamBillDetia = () => {
  SelectUserinfoDialogVisible.value = true

  //获取用户列表
  ApiGetBasicData_UserinfoPageListAsync(queryUserinfoParam).then((res) => {
    SelectUserinfoFormtableData.value = res.data.data
  })
}

//清空班组人员明细
const batchDeletioneamBillDetia = () => {
  TeamBillDetialData.value = []
}

// 搜索班组设置
const SearchTeamBill = () => {
  tableloading.value = true
  ApiGetCrew_TeamBillPageListAsync(queryTeamBillParam)
    .then((res) => {
      tableData.value = res.data.data
      queryTeamBillParam.PageIndex = res.data.pageIndex
      queryTeamBillParam.PageSize = res.data.pageSize
      queryTeamBillParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 关闭创建班组设置对话框
const CreateTeamBillhandleClose = () => {
  const formEl = CreateTeamBillFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
}

// 打开添加班组设置对话框
const addTeamBill = () => {
  centerDialogVisible.value = true

  //初始明细
  batchDeletioneamBillDetia()

  //获取用户信息
  ApiGetBasicData_UserinfoPageListAsync(queryUserinfoParam).then((res) => {
    UserinfoOptions.value = res.data.data
  })
  // 获取班组类型
  ApiGetCrew_TeamTypePageListAsync(queryTeamTypeParam).then((res) => {
    TeamTypeOptions.value = res.data.data
  })
}

// 确认添加班组设置
const CreateTeamBillDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (TeamBillDetialData.value.length < 1) {
        ElNotification({
          message: '请先添加人员',
          offset: 100,
          type: 'warning',
          duration: 2000
        })
        return
      }
      // 提取 TeamBillDetialData 中的 id 组成一个集合
      CreateTeamBillForm.userIds = TeamBillDetialData.value.map((item) => item.id)

      ApiCreateCrew_TeamBillAsync(CreateTeamBillForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateTeamBillhandleClose()
          SearchTeamBill()
        }
      })
    }
  })
}

// 删除单个班组设置
const DeleteTeamBillSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionTeamBill()
}

// 批量删除班组设置
const batchDeletionTeamBill = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionCrew_TeamBillAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchTeamBill()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// 获取用户选择项
const handleSelectionChange = (val: TeamBill[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  queryTeamBillParam.PageSize = e
  SearchTeamBill()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  queryTeamBillParam.PageIndex = e
  SearchTeamBill()
}

// 初次加载数据
onMounted(() => {
  SearchTeamBill()
})
</script>



<style lang="less"  scoped>
.TeamBillfunctionbutton {
  margin: 15px;
}

@import '../../assets/globle/index.css';
</style>
